const NodeRSA = require('node-rsa');
const fs = require('fs');

function nodeRsaDemo(){
    // 生成新的512位长度密钥
    const key = new NodeRSA({b: 512});
    
    const text = 'Hello RSA!';
    console.log('text', text);
    const encrypted = key.encrypt(text, 'base64');
    console.log('encrypted: ', encrypted);
    const decrypted = key.decrypt(encrypted, 'utf8');
    console.log('decrypted: ', decrypted);
}

// 通过生成密钥对进行加密解密
function generator(){
    let key = new NodeRSA({b: 512});
    key.setOptions({encryptionScheme: 'pkcs1'});

    let privatePem = key.exportKey('pkcs1-private-pem');
    console.log(privatePem)
    let publicPem  = key.exportKey('pkcs1-public-pem');
    console.log(publicPem)

    fs.writeFile('./pem/public.pem', publicPem, {'flag': 'w'}, (err) => {
        if(err){
            return console.error(err);
        }
        console.log('公钥已经保存');
    });

    fs.writeFile('./pem/private.pem', privatePem, {'flag': 'w'}, (err) => {
        if(err) throw err;
        console.log('私钥已经保存');
    });
}

const path = __dirname+'/pem';
const privatePemFile = path+'/private.pem';
const publicPemFile =  path+'/public.pem';

function encrypt(content){
    let data = fs.readFileSync(privatePemFile);
    let key = new NodeRSA(data);
    return key.encryptPrivate(content, 'base64','utf8');
}

function decrypt(content){
    let data = fs.readFileSync(publicPemFile);
    let key = new NodeRSA(data);
    return key.decryptPublic(content, 'utf8');;
}

// generator();

const content = 'hello nodejs';
console.log('text', content);
const encryptCxt = encrypt(content)
console.log('加密后', encryptCxt)
console.log('解密后', decrypt(encryptCxt));